package com.link.base.tencent.youtu.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.base.message.push.service.PushService;
import com.link.base.tencent.corpwx.agent.model.Agent;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.message.model.MessageBase;
import com.link.base.user.model.CoreUser;
import com.link.base.base.reception.model.WaitReception;
import com.link.base.base.reception.service.ReceptionService;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.message.service.AgentMessageService;
import com.link.base.tencent.secret.util.SecretUtil;
import com.link.base.tencent.youtu.dao.mybatis.mapper.YoutuMapper;
import com.link.base.tencent.youtu.model.*;
import com.link.base.tencent.youtu.util.FaceUtil;
import com.link.core.basic.model.UploadImgInfo;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 优图 service 实现
 *
 * @author ouyangzhenqiang
 * @date 2018/12/29
 */
@Service
public class YoutuServiceImpl implements YoutuService {
    /**
     * 项目信息RedisKey
     */
    private static final String YOUTU_REDISKEY = "TENCENT_YOUTU_APP_INFO_";
    /**
     * 触发分组个体数预警的数量值
     */
    private static final Integer GROUPWARNPERSON_NUM = 19800;
    /**
     * 分组个体数满仓值
     */
    private static final Integer GROUPFULLPERSON_NUM = 20000;
    /**
     * 项目下最大分组数量
     */
    private static final Integer APPFULLGROUP_NUM = 5000;
    /**
     * 魔法值
     */
    private static final String yStr = "Y";
    private static final String nStr = "N";

    @Resource
    private YoutuMapper youtuMapper;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private PushService pushService;
    @Resource
    private ReceptionService receptionService;
    @Resource
    private AgentMessageService agentMessageService;
    @Resource
    private AgentService agentService;

    @Override
    public PublicAppInfo getAppGroup(Store tempStore) throws Exception {
        Long storeId = tempStore.getStoreId();
        Long corpId = tempStore.getCorpId();
        PublicAppInfo publicAppInfo = new PublicAppInfo();
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            /* Redis中获取优图项目信息 */
            String corpYouturediskey = YOUTU_REDISKEY + corpId;
            // 腾讯云API_项目appId
            String redisAppId = j.hget(corpYouturediskey, "YOUTU_APPID");
            // 腾讯云API_项目appId对应的Link Id
            String redisAppLnkId = j.hget(corpYouturediskey, "YOUTU_APP_LNK_ID");
            // 腾讯云API_项目下分组总数量
            String redisAppGroupNum = j.hget(corpYouturediskey, "YOUTU_APP_GROUP_NUM");

            /* Redis中获取优图分组信息 */
            String storeRedisGroupId = "YOUTU_APP_GROUP_ID_" + storeId;
            // 项目下门店当前可用分组Id
            String redisGroupId = j.hget(corpYouturediskey, storeRedisGroupId);

            // 项目下门店当前可用分组Id对应的Link Id
            String storeRedisGroupLnkId = "YOUTU_APP_GROUP_LNK_ID_" + storeId;
            String redisGroupLnkId = j.hget(corpYouturediskey, storeRedisGroupLnkId);

            // 项目下门店当前可用分组下的个体数量
            String storeRedisGroupPersonNum = "YOUTU_APP_GROUP_PERSON_NUM_" + storeId;
            String redisGroupPersonNum = j.hget(corpYouturediskey, storeRedisGroupPersonNum);

            // 项目下门店预置的下一个可用分组Id
            String storeRedisNextGroupId = "YOUTU_APP_NEXT_GROUP_ID_" + storeId;
            String redisNextGroupId = j.hget(corpYouturediskey, storeRedisNextGroupId);

            // 项目下门店预置的下一个可用分组Id对应的Link Id
            String storeRedisNextGroupLnkId = "YOUTU_APP_NEXT_GROUP_LNK_ID_" + storeId;
            Long redisNextGroupLnkId = Long.parseLong(j.hget(corpYouturediskey, storeRedisNextGroupLnkId));

            // 项目下门店分组Id列表
            String storeRedisGroupIdList = "YOUTU_APP_GROUP_ID_LIST_" + storeId;
            String redisGroupIdList = j.hget(corpYouturediskey, storeRedisGroupIdList);

            if (StringUtils.isBlank(redisAppLnkId) || StringUtils.isBlank(redisAppId) || StringUtils.isBlank(redisAppGroupNum)) {
                RedisUtil.returnResource(j);
                throw new ServiceException("YOUTU-005");
            } else {
                if (StringUtils.isBlank(redisGroupId) || StringUtils.isBlank(redisGroupLnkId) || StringUtils.isBlank(redisGroupPersonNum)) {
                    LCLogger.info().withMessageKey("getAppGroup").withMessage("Redis中不存在分组信息，开始从数据库获取.").flush();

                    Group group = new Group();
                    /* 根据门店Id获取门店下的分组 */
                    List<Group> groupList = youtuMapper.getGroupListByStoreId(tempStore);
                    if (groupList.size() == 0) {
                        LCLogger.info().withMessageKey("getAppGroup").withMessage("DB中不存在任何分组信息，则新建项目下门店的第一个分组.").flush();
                        groupList = new ArrayList<Group>();
                        group.setGroupId(PasswordUtil.parseStrToMd5L32(String.valueOf(System.currentTimeMillis())));
                        group.setId(keyGenerateService.keyGenerate());
                        group.setPersonNum(0);
                        group.setAppLnkId(redisAppLnkId);
                        group.setStoreId(storeId);
                        group.interfaceCreateData(0L, 0L, corpId);
                        youtuMapper.groupInsertByInterface(group);
                        groupList.add(group);
                        LCLogger.info().withMessageKey("getAppGroup").withMessage("项目下分组加一.").flush();
                        redisAppGroupNum = String.valueOf(Integer.parseInt(redisAppGroupNum) + 1);
                        j.hset(corpYouturediskey, "YOUTU_APP_GROUP_NUM", redisAppGroupNum);
                    }
                    /* 构造Redis分组信息 */
                    String group_ids = "";
                    Integer personNum = 20000;
                    Group useGroup = new Group();
                    for (int i = 0; i < groupList.size(); i++) {
                        if (i == 0) {
                            /* 默认先取一个group对象，以防止下面获取个体数量最少分组时，条件不成立导致空指针 */
                            useGroup = groupList.get(0);
                        }
                        /* 拼接分组串，用于后续的人脸检索功能 */
                        group = groupList.get(i);
                        if (group_ids == "") {
                            group_ids = "\"" + group.getGroupId() + "\"";
                        } else {
                            group_ids += ",\"" + group.getGroupId() + "\"";
                        }
                        /* 取一个分组下个体数量最少的分组来使用 */
                        if (group.getPersonNum() <= personNum) {
                            personNum = group.getPersonNum();
                            useGroup = group;
                        }
                    }
                    redisGroupId = useGroup.getGroupId();
                    j.hset(corpYouturediskey, storeRedisGroupId, redisGroupId);

                    redisGroupLnkId = useGroup.getId().toString();
                    j.hset(corpYouturediskey, storeRedisGroupLnkId, redisGroupLnkId);

                    redisGroupPersonNum = useGroup.getPersonNum().toString();
                    j.hset(corpYouturediskey, storeRedisGroupPersonNum, redisGroupPersonNum);

                    redisGroupIdList = group_ids;
                    j.hset(corpYouturediskey, storeRedisGroupIdList, group_ids);
                }

                /* 统一控制Redis中分组，做出相应的判断 */
                /* 1. 判断分组下个体数量是否达到预警值 */
                if (Integer.parseInt(redisGroupPersonNum) >= GROUPWARNPERSON_NUM && StringUtils.isBlank(redisNextGroupId)) {
                    LCLogger.info().withMessageKey("getAppGroup").withMessage("分组下个体数量达到预警值，需要新建分组.").flush();
                    if (Integer.parseInt(redisAppGroupNum) < APPFULLGROUP_NUM) {
                        Group tempGroup = new Group();

                        redisNextGroupId = PasswordUtil.parseStrToMd5L32(String.valueOf(System.currentTimeMillis()));
                        j.hset(corpYouturediskey, storeRedisNextGroupId, redisNextGroupId);

                        tempGroup.setGroupId(redisNextGroupId);
                        tempGroup.setAppLnkId(redisAppLnkId);
                        redisNextGroupLnkId = keyGenerateService.keyGenerate();
                        tempGroup.setId(redisNextGroupLnkId);
                        tempGroup.interfaceCreateData(0L, 0L, corpId);
                        youtuMapper.groupInsertByInterface(tempGroup);

                        LCLogger.info().withMessageKey("getAppGroup").withMessage("项目下分组加一.").flush();
                        redisAppGroupNum = String.valueOf(Integer.parseInt(redisAppGroupNum) + 1);
                        j.hset(corpYouturediskey, "YOUTU_APP_GROUP_NUM", redisAppGroupNum);

                        j.hset(corpYouturediskey, storeRedisNextGroupLnkId, redisNextGroupLnkId.toString());
                        j.hset(corpYouturediskey, storeRedisGroupIdList, redisGroupIdList + ",\"" + redisNextGroupId + "\"");
                    } else {
                        throw new ServiceException("YOUTU-006", redisAppId);
                    }
                }
                /* 2. 判断分分组下个体数量是否达到限度 */
                if (Integer.parseInt(redisGroupPersonNum) >= GROUPFULLPERSON_NUM && !StringUtils.isBlank(redisNextGroupId)) {
                    LCLogger.info().withMessageKey("getAppGroup").withMessage("分组下个体数量达到限度，改用下一个分组Id.").flush();
                    redisGroupId = redisNextGroupId;
                    redisGroupLnkId = redisNextGroupLnkId.toString();
                    j.hset(corpYouturediskey, storeRedisGroupId, redisGroupId);
                    j.hset(corpYouturediskey, storeRedisGroupLnkId, redisGroupLnkId);
                    j.hset(corpYouturediskey, storeRedisGroupPersonNum, "0");
                    j.hset(corpYouturediskey, storeRedisNextGroupId, "");

                }
            }
            publicAppInfo.setGroupId(redisGroupId);
            publicAppInfo.setGroupRowId(redisGroupLnkId);
            publicAppInfo.setGroups(redisGroupIdList);
            LCLogger.info().withMessageKey("getAppGroup")
                    .withMessage("返回分组信息=> GroupId: " + redisGroupId + ", GroupLnkId: " + redisGroupLnkId
                            + ", GroupIdList: " + redisGroupIdList).flush();
        } finally {
            RedisUtil.returnResource(j);
        }
        return publicAppInfo;
    }

    @Override
    public String identify(String groupIdList, String imgUrl, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.identify(publicAppInfo.getSecret(), publicAppInfo.getAppId(), groupIdList, imgUrl);
    }

    @Override
    public String newperson(String groupIdList, String person_id, String imgUrl, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.newperson(publicAppInfo.getSecret(), publicAppInfo.getAppId(), groupIdList, person_id, imgUrl);
    }

    @Override
    public void delperson(String person_id, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        FaceUtil.delperson(publicAppInfo.getSecret(), publicAppInfo.getAppId(), person_id);
    }

    @Override
    public String newLinkPerson(Person record, Face face, Store tempStore) throws Exception {
        /* 新建person */
        Long personLnkId = keyGenerateService.keyGenerate();
        record.setId(personLnkId);
        record.interfaceCreateData(0L, 0L, tempStore.getCorpId());
        youtuMapper.linkPersonInsertByInterface(record);

        /* 新建group&person中间表记录 */
        GroupPerson groupPerson = new GroupPerson();
        groupPerson.setId(keyGenerateService.keyGenerate());
        groupPerson.setPersonLnkId(personLnkId.toString());
        groupPerson.setGroupLnkId(record.getGroupLnkId());
        groupPerson.interfaceCreateData(0L, 0L, tempStore.getCorpId());
        youtuMapper.linkGroupPersonInsertByInterface(groupPerson);

        /* 新建人脸 */
        face.setPersonLnkId(personLnkId.toString());
        face.setId(keyGenerateService.keyGenerate());
        face.interfaceCreateData(0L, 0L, tempStore.getCorpId());
        youtuMapper.linkFaceInsertByInterface(face);

        LCLogger.info().withMessageKey("newLinkPerson").withMessage("Redis中的person数量加一.").flush();
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            String corpYouturediskey = YOUTU_REDISKEY + tempStore.getCorpId();
            String storeRedisGroupPersonNum = "YOUTU_APP_GROUP_PERSON_NUM_" + tempStore.getStoreId();

            j.hset(corpYouturediskey, storeRedisGroupPersonNum,
                    String.valueOf((Integer.parseInt(j.hget(corpYouturediskey, storeRedisGroupPersonNum)) + 1)));
        } finally {
            RedisUtil.returnResource(j);
        }
        LCLogger.info().withMessageKey("newLinkPerson").withMessage("返回的personLnkId => " + personLnkId).flush();
        return personLnkId.toString();
    }

    @Override
    public String addface(String person_id, ArrayList<String> urls, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.addface(publicAppInfo.getSecret(), publicAppInfo.getAppId(), person_id, urls);
    }

    @Override
    public void addLinkFace(Face record, String corpId) throws Exception {
        LCLogger.info().withMessageKey("addLinkFace").withMessage("通过优图personId获取Link的personId.").flush();
        String youtuPersonId = record.getPersonId();
        Person person = new Person();
        person.setPersonId(youtuPersonId);
        person = youtuMapper.getLnkPersonIdByYoutuPersonId(person);
        // 个体下已有face数量
        int faceNum = person.getFaceNum();
        int len = 20;
        if (faceNum >= len) {
            LCLogger.info().withMessageKey("addLinkFace").withMessage("face数量大于等于20，需要删除旧的Link上的face&优图上的face").flush();
            Face face = new Face();
            face.setPersonLnkId(person.getId().toString());
            /* 获取个体下最旧的一张face，用于清空 */
            face = youtuMapper.getLastFaceByPersonId(face);
            /* 删除 link face */
            youtuMapper.deleteFaceById(face);
            /* 删除优图上的face */
            ArrayList<String> face_ids = new ArrayList<String>();
            face_ids.add(face.getFaceId());
            delface(youtuPersonId, face_ids, corpId);
        }

        /* 新建优图人脸 */
        ArrayList<String> urls = new ArrayList<String>();
        urls.add(record.getFaceUrl());
        String faceStr = addface(youtuPersonId, urls, corpId);
        JSONObject faceInfoObj = JSONObject.parseObject(faceStr);
        JSONObject data = faceInfoObj.getJSONObject("data");
        String faceId = data.getJSONArray("face_ids").getString(0);

        /* 新建Link人脸 */
        record.setFaceId(faceId);
        record.setPersonLnkId(person.getId().toString());
        record.setId(keyGenerateService.keyGenerate());
        record.interfaceCreateData(0L, 0L, Long.parseLong(corpId));
        youtuMapper.linkFaceInsertByInterface(record);
    }

    @Override
    public String delface(String person_id, ArrayList<String> face_ids, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.delface(publicAppInfo.getSecret(), publicAppInfo.getAppId(), person_id, face_ids);
    }

    @Override
    public String setinfo(String person_id, String person_name, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.setinfo(publicAppInfo.getSecret(), publicAppInfo.getAppId(), person_id, person_name);
    }

    @Override
    public String faceDetect(String imgUrl, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.faceDetect(publicAppInfo.getSecret(), publicAppInfo.getAppId(), imgUrl);
    }

    @Override
    public NormalObj faceCompare(String imgUrlA, String imgUrlB, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        String resultStr = FaceUtil.faceCompare(publicAppInfo.getSecret(), publicAppInfo.getAppId(), imgUrlA, imgUrlB);
        JSONObject jsonObj = JSONObject.parseObject(resultStr);
        JSONObject data = jsonObj.getJSONObject("data");
        NormalObj normalObj = new NormalObj();
        normalObj.setSimilarity(data.getString("similarity"));
        return normalObj;
    }

    @Transactional(rollbackFor = BasicServiceException.class)
    @Override
    public String setReception(Reception record, List<ReceptionList> receptionList, Store tempStore) throws Exception {
        /* 新建接待头 */
        Long receptionId = keyGenerateService.keyGenerate();
        record.setId(receptionId);
        record.setStoreId(tempStore.getStoreId());
        record.interfaceCreateData(0L, 0L, tempStore.getCorpId());
        youtuMapper.receptionInsertByInterface(record);
        /* 新建接待行 */
        for (int i = 0; i < receptionList.size(); i++) {
            ReceptionList temp = receptionList.get(i);
            temp.setReceptionId(receptionId.toString());
            temp.setStoreId(tempStore.getStoreId());
            temp.setId(keyGenerateService.keyGenerate());
            temp.interfaceCreateData(0L, 0L, tempStore.getCorpId());
            youtuMapper.receptionListInsertByInterface(temp);
        }
        return receptionId.toString();
    }

    @Override
    public Face getFaceInfoByReceptionId(String receptionId) throws Exception {
        Reception temp = new Reception();
        temp.setId(Long.parseLong(receptionId));
        temp = youtuMapper.getFaceInfoByReceptionId(temp);
        Face face = new Face();
        face.setFaceUrl(temp.getFaceUrl());
        face.setAge(temp.getAge());
        face.setGender(temp.getGender());
        face.setGlass(temp.getGlass());
        face.setExpression(temp.getExpression());
        face.setMask(temp.getMask());
        face.setHat(temp.getHat());
        face.setBeauty(temp.getBeauty());
        return face;
    }

    @Override
    public void updateReceptionById(String receptionId, Long userId) throws Exception {
        Reception temp = new Reception();
        temp.setId(Long.parseLong(receptionId));
        temp.setReceptionFlag("Y");
        temp.setUserId(userId);
        youtuMapper.updateReceptionById(temp);
    }

    @Override
    public void resetYoutu(String delReception, Store tempStore) throws Exception {
        /* 根据门店Id获取门店下的分组列表 */
        List<Group> groupList = youtuMapper.getGroupListByStoreId(tempStore);
        for (Group group: groupList) {
            Long groupLnkId = group.getId();
            /* 基于group&person中间表获取group下的所有person */
            GroupPerson temp = new GroupPerson();
            temp.setGroupLnkId(groupLnkId.toString());
            List<GroupPerson> groupPersonList = youtuMapper.getPersonListByGroupId(temp);
            for (int j = 0; j < groupPersonList.size(); j++) {
                temp = groupPersonList.get(j);
                // Link个体Id
                String personLnkId = temp.getPersonLnkId();
                // 优图个体Id
                String person_id = temp.getPersonId();
                Person person = new Person();
                person.setId(Long.parseLong(personLnkId));
                /* 获取个体下的所有人脸 */
                List<Face> faceList = youtuMapper.getFaceListByPersonId(person);
                ArrayList<String> arrayFaceList = new ArrayList<String>();
                for (int x = 0; x < faceList.size(); x++) {
                    arrayFaceList.add(faceList.get(x).getFaceId());
                }
                /* 删除优图person下所有人脸 */
                delface(person_id, arrayFaceList, tempStore.getCorpId().toString());
                /* 删除优图person */
                delperson(person_id, tempStore.getCorpId().toString());

                /* 删除Link person下的人脸 */
                youtuMapper.delFaceByPersonId(person);
            }
            temp.setCorpid(tempStore.getCorpId());
            /* 删除分组下的个体表记录基于分组Id */
            youtuMapper.delPersonByGroupId(temp);
            /* 删除分组个体中间表基于分组Id */
            youtuMapper.delGroupPersonByGroupId(temp);
            /* 删除分组 */
            youtuMapper.delGroupById(group);
        }
        /* 第三步、是否保留接待数据 */
        String yStr = "Y";
        if (!yStr.equals(delReception)) {
            Reception temp = new Reception();
            temp.setCorpid(tempStore.getCorpId());
            temp.setStoreId(tempStore.getStoreId());
            youtuMapper.delReception(temp);
            youtuMapper.delReceptionList(temp);
        }
    }

    @Override
    public String getgroupids(String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.getgroupids(publicAppInfo.getSecret(), publicAppInfo.getAppId());
    }

    @Override
    public String getpersonids(String group_id, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.getpersonids(publicAppInfo.getSecret(), publicAppInfo.getAppId(), group_id);
    }

    @Override
    public String getfaceids(String person_id, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        return FaceUtil.getfaceids(publicAppInfo.getSecret(), publicAppInfo.getAppId(), person_id);
    }

    @Override
    public Store getStoreInfoById(Long storeId) throws Exception {
        Store temp = new Store();
        temp.setStoreId(storeId);
        return youtuMapper.getStoreInfoById(temp);
    }

    @Transactional(rollbackFor = BasicServiceException.class)
    @Override
    public String newPersonFace(String receptionId) throws Exception {
        // 通过接待头Id获取接待上的face信息，并构造face对象
        Face temp = getFaceInfoByReceptionId(receptionId);
        // 获取当前登录用户的门店信息
        Store tempStore = new Store();
        CoreUser user = UserUtil.getUser();
        Long corpId = user.getCorpid();
        tempStore.setCorpId(corpId);
        Long accntId = user.getAcctId();
        tempStore.setStoreId(accntId);
        // 获取组信息
        PublicAppInfo publicAppInfo = getAppGroup(tempStore);
        /* 优图创建个体&face */
        String personId = PasswordUtil.parseStrToMd5L32(String.valueOf(System.currentTimeMillis()));
        String newPersonStr = newperson("\"" + publicAppInfo.getGroupId() + "\"", personId, temp.getFaceUrl(), corpId.toString());
        JSONObject newPersonObj = JSONObject.parseObject(newPersonStr);
        JSONObject data = newPersonObj.getJSONObject("data");
        String faceId = data.getString("face_id");
        /* 使用优图返回的faceId回写给Link */
        temp.setFaceId(faceId);

        /* Link创建个体&face */
        Person person = new Person();
        person.setGroupLnkId(publicAppInfo.getGroupRowId());
        person.setPersonId(personId);
        String personLnkId = newLinkPerson(person, temp, tempStore);

        /* 回写接待信息 */
        Long userId = user.getId();
        updateReceptionById(receptionId, userId);

        return personLnkId;

    }

    @Override
    public void personcome(YoutuImg record, Store tempStore) throws Exception {
        Reception reception = dealYoutuImgs(record, tempStore);
        LCLogger.info().withMessageKey("personcome").withMessage("接待表头行信息创建成功").flush();
        pushReceptionMessages(reception.getId().toString(), reception.getCorpid().toString(), tempStore);
        LCLogger.info().withMessageKey("personcome").withMessage("人脸识别信息推送成功").flush();
    }

    /**
    * 处理摄像头捕捉的图片，生成相应的的接待信息
    * @author Lizongting
    * @date 2018/12/14
    */
    public Reception dealYoutuImgs(YoutuImg record, Store tempStore) throws Exception {
        String isCode = codeCheck(record);
        // 人脸图片访问地址
        String faceHttpUrl = "";
        // 人身图片访问地址
        String personHttpUrl = "";
        if (yStr.equals(isCode)) {
            // 人脸图片
            faceHttpUrl = getHttpUrlByCode(record.getImgStr());
            LCLogger.info().withMessageKey("personcome").withMessage("faceHttpUrl => " + faceHttpUrl).flush();
            // 人身图片
            personHttpUrl = getHttpUrlByCode(record.getImgStr1());
            LCLogger.info().withMessageKey("personcome").withMessage("personHttpUrl => " + personHttpUrl).flush();
        } else if (nStr.equals(isCode)) {
            // 获取人脸图片
            faceHttpUrl = record.getUrl();
            if (org.apache.commons.lang.StringUtils.isBlank(faceHttpUrl)) {
                throw new ServiceException("YOUTU-007");
            }
            // 获取人身图片
            personHttpUrl = record.getUrl1();
            if (org.apache.commons.lang.StringUtils.isBlank(personHttpUrl)) {
                throw new ServiceException("YOUTU-008");
            }
        }

        /* 人脸分析 - 获取人脸信息 */
        String faceInfoStr = faceDetect(faceHttpUrl, tempStore.getCorpId().toString());
        JSONObject faceInfoObj = JSONObject.parseObject(faceInfoStr);
        JSONObject faceData = faceInfoObj.getJSONObject("data");
        JSONObject faceObj = faceData.getJSONArray("face").getJSONObject(0);

        /* 人脸检索 Top5 */
        PublicAppInfo publicAppInfo = getAppGroup(tempStore);
        String identifyStr = identify(publicAppInfo.getGroups(), faceHttpUrl, tempStore.getCorpId().toString());
        JSONObject identifyObj = JSONObject.parseObject(identifyStr);
        JSONObject data = identifyObj.getJSONObject("data");

        /* 构建接待头 */
        Reception reception = new Reception();
        reception.setFaceUrl(faceHttpUrl);
        reception.setPersonUrl(personHttpUrl);
        reception.setAge(faceObj.getString("age"));
        reception.setGender(faceObj.getString("gender"));
        reception.setGlass(faceObj.getString("glass"));
        reception.setExpression(faceObj.getString("expression"));
        reception.setMask(faceObj.getString("mask"));
        reception.setHat(faceObj.getString("hat"));
        reception.setBeauty(faceObj.getString("beauty"));

        /* 构建接待行 */
        List<ReceptionList> receptionList = new ArrayList<>();
        JSONArray candidates = data.getJSONArray("candidates");
        /* 需要对检索出来的top5记录去重，因为检索匹配的是人脸，极有可能匹配出来的人脸同属一个人 */
        for (int i = 0; i < candidates.size(); i++) {
            JSONObject candidatesItem = candidates.getJSONObject(i);
            // 相似度 低于80%的匹配记录将不予处理
            Double similarity = 80d;
            String tempPersonId = candidatesItem.getString("person_id");
            Double confidence = candidatesItem.getDouble("confidence");
            if (confidence > similarity) {
                Boolean isFindPerson = false;
                for (ReceptionList person: receptionList) {
                    if (tempPersonId.equals(person.getPersonId())) {
                        isFindPerson = true;
                        break;
                    }
                }
                if (!isFindPerson) {
                    ReceptionList temp = new ReceptionList();
                    temp.setPersonId(tempPersonId);
                    temp.setFaceId(candidatesItem.getString("face_id"));
                    temp.setConfidence(String.valueOf(confidence));
                    receptionList.add(temp);
                }
            }
        }

        /* 设置接待信息 */
        String receptionId = setReception(reception, receptionList, tempStore);
        Reception result = new Reception();
        result.setId(Long.parseLong(receptionId));
        result.setCorpid(tempStore.getCorpId());
        return result;
    }


    /**
     * 推送接待消息给门店相关人员
     * @author Lizongting
     * @date 2018/12/14
     * @param receptionId
     * @param corpId
     * @param tempStore
    */
    void pushReceptionMessages(String receptionId, String corpId, Store tempStore) {
        try {
            String message = "有客户进店啦，快打开营销助手接待吧！";
            /**
             * 基于生成的待接待头记录Id，调用待接待模块方法获取待接待列表下top5中，
             * 匹配度最高的用户，并试图获取其对应的Link用户姓名
             */
            WaitReception waitReception = new WaitReception();
            waitReception.setId(Long.parseLong(receptionId));
            waitReception = receptionService.queryTopConfidenceAccount(waitReception);
            if (waitReception != null) {
                String topAccountName = waitReception.getTopAccountName();
                String topConfidence = waitReception.getTopConfidence();
                // 匹配度高于90%的客户才算明确了身份的客户，否则此处一律视为新客户
                int mapConfidence = 90;
                if (StringUtils.isNotBlank(topConfidence)) {
                    if (Float.valueOf(topConfidence) > mapConfidence && StringUtils.isNotBlank(topAccountName)) {
                        LCLogger.info().withMessageKey("personcome").withMessage("客户进店匹配老客户 => " + topAccountName).flush();
                        message = "您的客户【" + topAccountName + "】进店了，快去接待吧！";
                    }
                }
            }
            // 根据门店Id获取门店所有用户
            List<Store> userList = youtuMapper.getStoreUserListByStoreId(tempStore);
            for (Store item: userList) {
                Long userId = item.getUserId();
                if (userId != null) {
                    pushService.pushInfoRightAway(
                        "门店接待", message, userId, "reception", Long.parseLong(receptionId), "Y", "Y");
                }
            }
            //推送消息到企业微信用户
            List<String> userIdList = new ArrayList<>();
            //添加到企业微信推送列表中
            userIdList.add("@all");
            Agent agent = new Agent();
            agent.setAgentId(AgentIdUtil.CORPWX_LINKGUIDE_AGENTID);
            agent = agentService.queryAgentById(agent);
            String url = agent.getHomeUrl() + "&moduleType=reception&moduleId=" + receptionId;
            MessageBase messageBase = new MessageBase();
            messageBase.setUserIdList(userIdList);
            messageBase.setAgentId(agent.getAgentId());
            agentMessageService.sendAgentTextCardMsg(messageBase, message,"客户进店通知", url, "查看详情");
        } catch (Exception e) {
            LCLogger.info().withMessageKey("personcome").withMessage("set push note error => " + e.getMessage()).flush();
        }
    }

    @Override
    public NormalObj faceVerify(String personId, String imgUrl, String corpId) throws Exception {
        PublicAppInfo publicAppInfo = SecretUtil.getExistSecret(corpId);
        String resultStr = FaceUtil.faceVerify(publicAppInfo.getSecret(), publicAppInfo.getAppId(), personId, imgUrl);
        JSONObject jsonObj = JSONObject.parseObject(resultStr);
        JSONObject data = jsonObj.getJSONObject("data");
        NormalObj normalObj = new NormalObj();
        normalObj.setConfidence(data.getString("confidence"));
        normalObj.setIsmatch(data.getString("ismatch"));
        return normalObj;
    }

    @Override
    public String getHttpUrlByCode(String code) throws Exception {
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("YOUTU-009");
        }
        /* 存储图片至服务器，获取图片HTTP链接 */
        UploadImgInfo uploadImgInfoA = ImageUtil.UploadImage(code, "youtu-face");
        return uploadImgInfoA.getFileHttpPath();
    }

    @Transactional(rollbackFor = BasicServiceException.class)
    @Override
    public void refreshPersonFace(String personId, String receptionId) throws Exception {
        /* 增加人脸 */
        Face temp = getFaceInfoByReceptionId(receptionId);
        temp.setPersonId(personId);
        CoreUser user = UserUtil.getUser();
        Long corpId = user.getCorpid();
        addLinkFace(temp, corpId.toString());

        /* 回写接待信息 */
        Long userId = user.getId();
        updateReceptionById(receptionId, userId);
    }

    @Override
    public void safeCheck(String token) throws Exception {
        String jinwanchiji = "jinwanchiji123";
        if (!jinwanchiji.equals(token)) {
            throw new ServiceException("YOUTU-010");
        }
    }

    @Override
    public Store storeCheck(Long storeId) throws Exception {
        Store tempStore;
        if (storeId != null) {
            throw new ServiceException("YOUTU-011");
        } else {
            tempStore = getStoreInfoById(storeId);
            if (tempStore == null) {
                throw new ServiceException("YOUTU-012", String.valueOf(storeId));
            }
        }
        return tempStore;
    }

    @Override
    public String codeCheck(YoutuImg record) throws Exception {
        String isCode = record.getIsCode();
        if (StringUtils.isBlank(isCode)) {
            throw new ServiceException("YOUTU-013");
        }
        if (!yStr.equals(isCode) && !nStr.equals(isCode)) {
            throw new ServiceException("YOUTU-014");
        }
        return isCode;
    }

}
